// Interactive List Box Implementation extracted from ChainGREP.jsx
// This provides a reusable listbox component with up/down/remove functionality

/**
 * Creates an interactive listbox UI with controls for reordering and removing items
 * @param {Array} itemArray - Array of items to display in the listbox
 * @param {Object} options - Configuration options for the listbox
 * @returns {Object} The created window object
 */
function createInteractiveListBox(itemArray, options) {
    var defaultOptions = {
        windowTitle: "Interactive List Box",
        panelTitle: "Item List",
        columnTitles: ["Name", "Type", "Find", "Change"],
        columnWidths: [350, 50, 100, 100],
        showHeaders: true,
        multiselect: true
    };
    
    // Merge options with defaults
    options = options || {};
    for (var prop in defaultOptions) {
        if (options[prop] === undefined) {
            options[prop] = defaultOptions[prop];
        }
    }

    var w = new Window("dialog", options.windowTitle, undefined);
    w.orientation = "column";

    // Create list panel
    var lbPanel = w.add("Panel", undefined, options.panelTitle);
    lbPanel.alignment = ["fill", "fill"];
    lbPanel.margins = [10, 20, 10, 10];

    // Create listbox
    var list = lbPanel.add("listbox", undefined, undefined, {
        numberOfColumns: options.columnTitles.length,
        showHeaders: options.showHeaders,
        columnTitles: options.columnTitles,
        multiselect: options.multiselect,
        columnWidths: options.columnWidths
    });
    list.alignment = ["fill", "fill"];
    list.preferredSize.height = 350;
    list.preferredSize.width = 420;

    // Populate list with items
    for (var i = 0; i < itemArray.length; i++) {
        var lItem = list.add("item", itemArray[i].name || itemArray[i].text || "Item " + (i + 1));
        lItem.itemData = itemArray[i];
        if (itemArray[i].subItems) {
            for (var j = 0; j < Math.min(itemArray[i].subItems.length, options.columnTitles.length - 1); j++) {
                lItem.subItems[j].text = itemArray[i].subItems[j];
            }
        }
        if (itemArray[i].helpTip) {
            lItem.helpTip = itemArray[i].helpTip;
        }
    }

    // Control buttons group
    var ctrlGroup = lbPanel.add("group");
    ctrlGroup.orientation = "row";
    ctrlGroup.alignment = ["center", "top"];
    
    var upBtn = ctrlGroup.add("button", undefined, "Up");
    var downBtn = ctrlGroup.add("button", undefined, "Down");
    ctrlGroup.add("StaticText", undefined, "|");
    var removeBtn = ctrlGroup.add("button", undefined, "Remove");

    // Event handlers
    upBtn.onClick = function () {
        if (list.selection == null) return;
        fixSelection(list.selection);
        var first = list.selection[0].index;
        if (first == 0 || !continuous(list.selection)) return;
        var last = first + list.selection.length;
        for (var i = first; i < last; i++) {
            swap(list.items[i - 1], list.items[i]);
        }
        list.selection = null;
        for (var i = first - 1; i < last - 1; i++) {
            list.selection = i;
        }
    };

    downBtn.onClick = function () {
        if (list.selection == null) return;
        fixSelection(list.selection);
        var last = list.selection[list.selection.length - 1].index;
        if (last == list.items.length - 1 || !continuous(list.selection)) return;
        var first = list.selection[0].index;
        for (var i = last; i >= first; i--) {
            swap(list.items[i + 1], list.items[i]);
        }
        list.selection = null;
        for (var i = first + 1; i <= last + 1; i++) {
            list.selection = i;
        }
    };

    removeBtn.onClick = function () {
        if (list.selection == null) return;
        var sel = list.selection[0].index;
        for (var i = list.selection.length - 1; i >= 0; i--) {
            list.remove(list.selection[i]);
        }
        if (sel > list.items.length - 1) {
            list.selection = null;
        } else {
            list.selection = sel;
        }
    };

    // Helper functions
    function continuous(sel) {
        return sel.length == (sel[sel.length - 1].index - sel[0].index + 1);
    }

    function swap(x, y) {
        var temp = {};
        temp.text = x.text;
        temp.itemData = x.itemData;
        temp.subItems = [];
        for (var i = 0; i < x.subItems.length; i++) {
            temp.subItems.push(x.subItems[i].text);
        }

        x.text = y.text;
        x.itemData = y.itemData;
        for (var i = 0; i < y.subItems.length; i++) {
            x.subItems[i].text = y.subItems[i].text;
        }

        y.text = temp.text;
        y.itemData = temp.itemData;
        for (var i = 0; i < temp.subItems.length; i++) {
            y.subItems[i].text = temp.subItems[i];
        }
    }

    function fixSelection(sel) {
        if ((sel[sel.length - 1].index - sel[0].index + 1) <= 0) {
            list.selection = null;
            for (var i = sel[sel.length - 1].index; i < sel[0].index + 1; i++) {
                list.selection = i;
            }
        }
    }

    // Add OK and Cancel buttons
    var btnGroup = w.add("group");
    btnGroup.orientation = "row";
    btnGroup.alignment = ["right", "top"];
    
    var cancelBtn = btnGroup.add("button", undefined, "Cancel");
    var okButton = btnGroup.add("button", undefined, "OK");

    cancelBtn.onClick = function () {
        w.close(0);
    };

    okButton.onClick = function () {
        w.close(1);
    };

    return w;
}

/**
 * Example usage of the interactive listbox
 */
function exampleUsage() {
    // Sample data
    var items = [
        { name: "Query 1", subItems: ["GREP", "find1", "change1"], helpTip: "Find: pattern1\nChange: replacement1" },
        { name: "Query 2", subItems: ["GREP", "find2", "change2"], helpTip: "Find: pattern2\nChange: replacement2" },
        { name: "Query 3", subItems: ["GREP", "find3", "change3"], helpTip: "Find: pattern3\nChange: replacement3" }
    ];

    var dialog = createInteractiveListBox(items, {
        windowTitle: "Example List Box",
        panelTitle: "Select and Arrange Items"
    });

    var result = dialog.show();
    if (result == 1) {
        var selectedItems = [];
        for (var i = 0; i < dialog.list.items.length; i++) {
            selectedItems.push(dialog.list.items[i].itemData);
        }
        alert("Selected " + selectedItems.length + " items");
        return selectedItems;
    }
    return null;
}

// Uncomment to test
// exampleUsage();